import json
import re
from django.shortcuts import render,redirect
from django.views import View
from django import http
from django.conf import settings
from meiduo1.utils.classusers import MyLoginRequiredMiXinView
from meiduo1.utils.email import generate_verify_url,decode_token
from meiduo1.utils.response_code import RET
from .models import User, Address
from django.contrib.auth import authenticate, login, logout
from celery_test.email.tasks import email_url

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        user_name = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        cpwd = request.POST.get('cpwd')
        phone = request.POST.get('phone')
        msg_code = request.POST.get('msg_code')
        allow = request.POST.get('allow')
        if not all([user_name,pwd,cpwd,phone,msg_code,allow]):#all()其中一个参数为真就为真
            return http.HttpResponseForbidden('参数不全')
        if pwd != cpwd:
            return http.HttpResponseForbidden('密码不一致')
        if not re.match(r'1[3-9]\d{9}',phone):
            return http.HttpResponseForbidden('填写正确的号码')

        #验证码的校验

        if allow != 'on':
            return http.HttpResponseForbiddenh('请选择协议才能注册')

        user = User.objects.create_user(username=user_name,password=pwd,mobile=phone)

        redirect('127.0.0.1:8000')
        return redirect

class CheckNameView(View):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        data = {
            "count":count
        }

        return http.JsonResponse(data)

class CheckMobilView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "count":count
        }
        return http.JsonResponse(data)

class LoginUserView(View):
    def get(self,request):
        return render(request,'login.html')

    def post(self,request):

        #获取参数
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        remembered =request.POST.get('remembered')
        #为空校验
        if not all([username,password,remembered]):
            return http.HttpResponseForbidden('请填写完整')
        #用户名校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('用户名格式不正确')
        #密码的校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden('密码格式不正确或密码错误')
        #检查用户名和密码的正确性
        user = authenticate(username=username, password=password)
        if not user:
            return http.HttpResponseForbidden('账号或者密码错误')
        #状态保持
        login(request,user)#用户的信息存到session中
        #设置状态保持的时间
        if remembered=='on':
            request.session.set_expiry(3600*24*2)
        else:
            request.session.set_expiry(0)

        # 返回一个响应
        response = redirect('/')
        response.set_cookie('username',user.username,3600*24*2)
        return response

class LogoutView(View):
    def get(self,request):
        #清除数据
        logout(request)
        #清除cookie
        response = redirect('/')
        response.delete_cookie('username')
        return response

class InfoView(MyLoginRequiredMiXinView):
    def get(self,request):
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }
        return render(request,'user_center_info.html',context=context)

class EmailView(MyLoginRequiredMiXinView):
    def put(self,request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        email = dict_data.get("email")

        # 2,校验参数
        # 2.1 为空校验
        if not email:
            return http.HttpResponseForbidden("参数不全")

        # 2.2 格式校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden("邮件格式有误")
        varyfie = generate_verify_url(request.user)
        # send_mail(subject='美多商城',
        #           message=varyfie,
        #           from_email=settings.EMAIL_FROM,
        #           recipient_list=[email])
        email_url.delay(varyfie,email)
        # 4,数据入库
        request.user.email = email
        request.user.save()

        # 5,返回响应
        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})

class AddressView(MyLoginRequiredMiXinView):
    def get(self,request):
        addresses = request.user.addresses.filter(is_deleted=False)

        # 2,数据拼接
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
            }
            addresses_list.append(address_dict)

        context = {
            "addresses": addresses_list,
            "default_address_id": request.user.default_address_id
        }
        return render(request,'user_center_site.html',context=context)

class EmailactivView(View):
    def get(self, request):
        # 1,获取token参数
        token = request.GET.get("token")

        # 2,校验参数
        if not token:
            return http.HttpResponseForbidden("token丢失")

        user = decode_token(token)

        if not user:
            return http.HttpResponseForbidden("token过期")

        # 3,数据入库(修改邮箱的激活器状态)
        user.email_active = True
        user.save()

        # 4,返回响应(重定向到个人中心)
        return redirect('/info')

class AddressCreateView(MyLoginRequiredMiXinView):
    def post(self, request):
        # 1,获取参数
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("参数不全")

        # 3,数据入库
        dict_data["user"] = request.user
        address = Address.objects.create(**dict_data)

        # 4,返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
        }
        return http.JsonResponse({"code": RET.OK, "address": address_dict})

class AddressUpdateView(MyLoginRequiredMiXinView):
    def put(self,request,address_id):
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("参数不全")

        # 3,数据入库
        address = Address.objects.get(id=address_id)
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        # 4,返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,
        }
        return http.JsonResponse({"code": RET.OK, "address": address_dict})

    def delete(self, request, address_id):
        # 1,获取地址对象
        address = Address.objects.get(id=address_id)

        # 2,修改地址的is_deleted属性,入库
        address.is_deleted = True
        address.save()

        # 3,返回响应
        return http.JsonResponse({"code": RET.OK})

class AddressDefaultView(MyLoginRequiredMiXinView):
        def put(self,request,address_id):
            request.user.default_address_id= address_id
            request.user.save()
            return http.JsonResponse({'code': RET.OK})#josn 类型返回的是字典类型

class AddressTitleView(MyLoginRequiredMiXinView):
        def put(self,request,address_id):
            title = json.loads(request.body.decode()).get('title')
            #为空校验
            if not title:
                return http.HttpResponseForbidden('参数不全')
            ret = Address.objects.filter(id=address_id).update(title=title)
            if ret==0:
                return http.HttpResponseForbidden("修改失败")
            return http.JsonResponse({'code':RET.OK})